import { Component, OnInit, Input, ElementRef, ViewChild } from "@angular/core";
import { TranslateService } from "@ngx-translate/core";
import { AuthGuardService } from "../../@core/auth-guard-service.guard";

@Component({
  selector: "app-modal",
  templateUrl: "./modal.component.html",
  styleUrls: ["./modal.component.less"],
})
export class ModalComponent implements OnInit {
  @ViewChild("textareaVal", { read: ElementRef }) textareaVal: ElementRef;
  
  constructor(
    private elr: ElementRef,
    private translate: TranslateService,
    private authGuardService: AuthGuardService
  ) { }

  parent: HTMLElement;
  i18nValues: any; //国际化变量
  headerTitle: any;
  isInputError: boolean = false;
  radioGroupStyle: any = {
    "margin-bottom": "5px",
    "padding-left": "20px",
    height: "auto",
    "max-height": "500px",
  };
  formList: any;
  questionJson: any = {
    "1": "",
    "2": "",
    "3": "",
    "4": "",
    "5": "",
    "6": "",
    "7": "",
    "8": "",
  };
  gender: string = "";
  checkBoxSelected: string[] = [];
  @Input() data: any;

  log($event, type) {
    if (type === "9") {
      this.gender = $event;
    } else {
      if (type === "3") {
        let val = $event?.value?.value;
        if (val) {
          if (!this.checkBoxSelected.includes(val)) {
            if ($event.isChecked) {
              this.checkBoxSelected.push(val);
            }
          } else {
            if (!$event.isChecked) {
              this.checkBoxSelected.splice(
                this.checkBoxSelected.indexOf(val),
                1
              );
            }
          }
          this.questionJson[type] = this.checkBoxSelected.sort().join("");
        }
      } else if (type === "7") {
        this.questionJson[type] = $event.target.value;
      } else {
        this.questionJson[type] = $event;
      }
    }
  }

  ngOnInit() {
    this.formList = this.data.questionnaire;
    this.i18nValues = this.translate.instant("home");
    this.headerTitle = this.i18nValues["panelText"][0];
    this.parent = this.elr.nativeElement.parentElement;
    let a = (window as any).sessionStorage.getItem("questionnaireKey");
    if (a) {
      a = JSON.parse(a);
      this.questionJson = a.o;
      this.gender = a.g;
    }
  }

  values: any;
  
  close(isCancel) {
    if (isCancel) {
      this.data.onClose("", isCancel);
    } else {
      this.values = Object.values(this.questionJson);
      if ((this.values[0] != 'female') && (this.values[0] != 'male')) {
        this.authGuardService.showModalPanel("warning", "请先完成问卷调查！");
      } else {
        this.data.onClose({ g: this.gender, o: this.questionJson }, isCancel);
        sessionStorage.removeItem('questionnaireKey');
      }
    }
  }

  verifyTextarea(e) {
    let textEle = this.textareaVal.nativeElement;
    textEle.value = e.target.value.substring(0, 300);
  }
}
